from sklearn.datasets import load_iris
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# 加载数据
iris = load_iris()
X, y = iris.data, iris.target

# 划分训练和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 建立模型（K=3）
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, y_train)

# 预测和评估
y_pred = knn.predict(X_test)
print("准确率：", accuracy_score(y_test, y_pred))
